//
//  GluMeasurVc.m
//  CareRingApp
//
//  Created  on 2025/2/13.
//  血糖测量
    

#import "GluMeasurVc.h"
#import <Masonry/Masonry.h>
#import <QMUIKit/QMUIKit.h>
#import "ConfigModel.h"
#import "CircularProgressView.h"
#import "GluNetObj.h"
#import "UIViewController+Custom.h"
#import "CADeviceInfo+description.h"
//#import "DeviceCenter.h"
//#import "AccountCenter.h"
#import "NSDate+HMTools.h"
//#import "LTSRingSDK+Desc.h"
#import "GluReportDetailVc.h"
#import "UIViewController+Custom.h"
#import "DmdbGlucose.h"
#import "TokenBucket.h"
#import "CARingSDK+Desc.h"


@interface GluMeasurVc ()

@property(strong, nonatomic) QMUIButton *startBtn,  *reReqBtn;
//@property(assign, nonatomic) BOOL isMeasuring;

@property(strong, nonatomic)CircularProgressView *circleProgressView; // 环形进度条

@property(assign, nonatomic)NSUInteger maxDataCount;

@property(strong, nonatomic)GluNetObj *gluNetObj; // 收集数据,网络请求

@property(strong, nonatomic)QMUIButton *selectBtn;

@property(assign, nonatomic)BOOL after_2_hor, fasting;

@property(strong, nonatomic)UILabel *netTipsLabel; //网络访问中的提示

@property(strong, nonatomic)UILabel *measuringTipsLabel; //获取ppg数据中的提示


@property(strong, nonatomic)DmdbGlucose *dbGlucoseObj;

@property(strong, nonatomic)NSDate *uploadPPgDate, *reqResultDate;

@property(strong, nonatomic)TokenBucket *tokenBucket; // 令牌桶计时

//@property(strong, nonatomic)NSString *mid; //
@property(strong, nonatomic)dispatch_source_t tipTimer;
@end

@implementation GluMeasurVc

- (void)viewDidLoad {
    
 
    
    [super viewDidLoad];
    self.after_2_hor = NO; //默认 饭后2小时
    self.fasting = !self.after_2_hor;
    self.maxDataCount = 5 * (60 * 100); // 100hz, 测量5分钟
    
    [self initUI];
    
    self.startBtn.enabled = CARingSDK.instance.currentDevice.isConnected;


    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
}

-(void)initUI
{
  
    
    UIView *selectCnt = [UIView new]; //选择时间的content
    UIView *circleCnt = [UIView new]; //进度条的 content
    
    [self.view addSubview:selectCnt];

    [self.view addSubview:circleCnt];
    
    [selectCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(selectCnt.superview);
        make.top.equalTo(selectCnt.superview).offset(10);
        make.height.equalTo(@40);
    }];
    
//    selectCnt.backgroundColor = UIColor.greenColor;
    // 选择
    //
   
    
    
    [selectCnt addSubview:self.selectBtn];
    [self.selectBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.selectBtn.superview);
        make.top.equalTo(self.selectBtn.superview);
        make.height.equalTo(self.selectBtn.superview);
    }];
    
    if (self.fasting) {
        [_selectBtn setTitle:@"Fasting for 8 hours" forState:UIControlStateNormal]; // 默认

    }
    
    if (self.after_2_hor) {
        [_selectBtn setTitle:@"Within 2 hours meal" forState:UIControlStateNormal]; // 默认
    }
    
//    [self.selectBtn addTarget:self action:@selector(selectMeasureType:) forControlEvents:UIControlEventTouchUpInside];
    
    [circleCnt mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(selectCnt.mas_bottom).offset(30);
        make.height.equalTo(circleCnt.mas_width);
        make.centerX.equalTo(circleCnt.superview.mas_centerX);
        
        make.width.equalTo(circleCnt.superview.mas_width).multipliedBy(3/5.0f);
    
    }];
    [circleCnt addSubview:self.circleProgressView];
    [self.circleProgressView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.circleProgressView.superview);
    }];
    
    [self.view layoutIfNeeded];
    
//    [self.circleProgressView setProgress:0.1 animated:NO];

    
    [self.view addSubview:self.startBtn];
    
    [self.startBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.equalTo(@44);
        make.width.equalTo(self.startBtn.superview.mas_width).multipliedBy(3.0/4);
        make.bottom.equalTo(self.startBtn.superview.mas_bottom).inset(30);
//        make.top.equalTo(self.symptomSelectView.mas_bottom).offset(15);
        
    }];
    self.reReqBtn.hidden = YES;
    [self.view addSubview:self.reReqBtn];
    [self.reReqBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.bottom.equalTo(self.startBtn);
    }];
    
    // 网络提示
    [self.view addSubview:self.netTipsLabel];
    self.netTipsLabel.hidden = YES;
    [self.netTipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(circleCnt.mas_bottom).offset(10);
        make.leading.equalTo(self.netTipsLabel.superview.mas_leading).offset(20);
        make.trailing.equalTo(self.netTipsLabel.superview.mas_trailing).inset(20);

    }];
    
    [self.view addSubview:self.measuringTipsLabel];
    [self.measuringTipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.equalTo(self.netTipsLabel);
    }];
    self.measuringTipsLabel.hidden = YES;
    
    [self.view layoutIfNeeded];
    self.status = GLU_STA_INIT;
    
}



// 选择测量的时间类型
//-(void)selectMeasureType:(QMUIButton *)btn {
//    
//    if (self.status != GLU_STA_INIT) {
//        return;
//    }
//    
//    UIAlertController *sheetControl  = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:_L(L_CANCEL) style:UIAlertActionStyleCancel handler:nil];
//    [sheetControl addAction:cancel];
//    
//    WEAK_SELF
//    UIAlertAction *aft2horAction = [UIAlertAction actionWithTitle:_L(L_tx_aft_meal_2_hor) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        STRONG_SELF
//        [strongSelf.selectBtn setTitle:_L(L_tx_aft_meal_2_hor) forState:UIControlStateNormal];
//        strongSelf.after_2_hor = YES;
//        strongSelf.fasting = !strongSelf.after_2_hor ;
//        strongSelf.gluNetObj.fasting = strongSelf.fasting;
//        strongSelf.gluNetObj.within2HrsMeal = strongSelf.after_2_hor;
//    }];
//    
//    [sheetControl addAction:aft2horAction];
//    UIAlertAction *fastingAction = [UIAlertAction actionWithTitle:_L(L_tx_aft_fasting_hor)
//                                                             style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        STRONG_SELF
//        [strongSelf.selectBtn setTitle:_L(L_tx_aft_fasting_hor) forState:UIControlStateNormal];
//        strongSelf.after_2_hor = NO;
//        strongSelf.fasting = !strongSelf.after_2_hor ;
//        strongSelf.gluNetObj.fasting = strongSelf.fasting;
//        strongSelf.gluNetObj.within2HrsMeal = strongSelf.after_2_hor;
//    }];
//    [sheetControl addAction:fastingAction];
//    
//    [self.weakNavControl presentViewController:sheetControl animated:YES completion:nil];
//    
//}

-(void)startBtnClick:(QMUIButton *)btn {

    if (self.status == GLU_STA_INIT) {
        // 点击 开始测量
//        if (![DeviceCenter instance].isSyncComplete) { // 同步未完成
//            [self showAlertWarningWithTitle:@"Tips" Msg:_L(L_TXT_SYNC_DATA_NOT_FIN) btnOk:_L(L_OK) OkBLk:^{
//                
//            } CancelBtn:nil CancelBlk:nil Compelete:nil];
//            
//            return;
//        }
        
        if ([CARingSDK instance].currentDevice.isCharging) {
            NSString *msg = _L2(L_TXT_REASON_IS_CHARGING);

            [[LTPHud Instance] showText:msg];

            return;
        }
        
        if (CARingSDK.instance.currentDevice.isConnected) {
            
            [CARingSDK.instance functionTurnGlucosePPgMeasure:YES];// Start LED single test
            
        } else {
            
            DebugNSLog(@"Send Start ppg led single test Bluetooth disconnected, not sent");
        }
        
        
    }
    
    if (self.status == GLU_STA_COLLECTING) {
        // 收集数据中 点击取消还原
        DebugNSLog(@"血糖下发  停止 2 !");
//        [DeviceCenter.instance.sdk functionTurnGlucosePPgMeasure:NO]; // 停止 led单测
//        self.status = GLU_STA_INIT;
        [CARingSDK.instance functionLedMeasure:NO LedColor:0 AutoAdjBri:YES Current:0 SampleRate:2];

    }
    
    
}

// 重新网络请求
-(void)reReqBtnClick:(QMUIButton *)btn {
    
    if (self.status == GLU_STA_UPLOAD_DATA_FAIL) {
        self.status = GLU_STA_UPLOAD_DATA; // 重传
    }
    
    if (self.status == GLU_STA_WAIT_RESULT_FAIL) {
        self.status = GLU_STA_WAIT_RESULT;//重新获取结果
    }
    
}

-(void)freshStartBtnBgColor
{
    if (self.startBtn.isSelected) {
        // 测量中 显示取消 红色
        _startBtn.backgroundColor = UIColor.redColor;

    }
    
    if (!self.startBtn.isSelected) {
        // 未测量 显示 开始 蓝色
        _startBtn.backgroundColor = UIColor.blueColor;

    }
}

-(void)freshNetTips
{
    if (self.status == GLU_STA_INIT) {
        self.netTipsLabel.hidden = YES;
        self.netTipsLabel.attributedText = nil;
    }
    
    // netTipsLabel
    if (self.status == GLU_STA_UPLOAD_DATA) {
        self.netTipsLabel.hidden = NO;
        // 计算倒计时
        int countDown = 30 - [[NSDate date] timeIntervalSinceDate:self.uploadPPgDate];
        if (countDown < 0) {
            countDown = 0;
        }
        NSString *cntString = [NSString stringWithFormat:@"Estimated time: %d s", countDown];
        
        NSString *netKeep = @"Please make sure that your phone is connected to the Internet properly, otherwise measurement may be delayed or unsuccessful.";;
        
        NSMutableAttributedString *tipString = [UIViewController bigSmallAttrString:[NSString stringWithFormat:@"%@\r\n\r\n", @"Uploading data…"] FontA:[UIFont fontWithName:FONT_ARIAL_BOLD size:21] TxtColorA:UIColor.whiteColor StrB:[NSString stringWithFormat:@"%@\r\n\r\n%@", cntString, netKeep] FontB:[UIFont systemFontOfSize:16] TxtColorB:UIColor.lightGrayColor];
        self.netTipsLabel.attributedText = tipString;
    }
    
    if (self.status == GLU_STA_WAIT_RESULT) {
        self.netTipsLabel.hidden = NO;

        int countDown = 30 - [[NSDate date] timeIntervalSinceDate:self.reqResultDate];
        if (countDown < 0) {
            countDown = 0;
        }
        
        NSString *cntString = [NSString stringWithFormat:@"Estimated time: %d s", countDown];
        
        NSString *netKeep = @"Please make sure that your phone is connected to the Internet properly, otherwise measurement may be delayed or unsuccessful.";;
        
        NSMutableAttributedString *tipString = [UIViewController bigSmallAttrString:[NSString stringWithFormat:@"%@\r\n\r\n", @"Waiting for measurement results…"] FontA:[UIFont fontWithName:FONT_ARIAL_BOLD size:21] TxtColorA:UIColor.whiteColor StrB:[NSString stringWithFormat:@"%@\r\n\r\n%@", cntString, netKeep] FontB:[UIFont systemFontOfSize:16] TxtColorB:UIColor.lightGrayColor];
        self.netTipsLabel.attributedText = tipString;
    }
    
    if (self.status == GLU_STA_UPLOAD_DATA_FAIL) {
        self.netTipsLabel.hidden = NO;

        NSMutableAttributedString *tipString = [UIViewController bigSmallAttrString:[NSString stringWithFormat:@"%@\r\n", @"Upload failed due to network issues!"] FontA:[UIFont systemFontOfSize:16] TxtColorA:UIColor.lightGrayColor StrB:nil FontB:nil TxtColorB:nil];
        self.netTipsLabel.attributedText = tipString;
    }
    
    if (self.status == GLU_STA_WAIT_RESULT_FAIL) {
        self.netTipsLabel.hidden = NO;

        NSMutableAttributedString *tipString = [UIViewController bigSmallAttrString:[NSString stringWithFormat:@"%@\r\n", @"Failed to request measurement result due to network issues!"] FontA:[UIFont systemFontOfSize:16] TxtColorA:UIColor.lightGrayColor StrB:nil FontB:nil TxtColorB:nil];
        self.netTipsLabel.attributedText = tipString;
    }
    
    if (self.status != GLU_STA_UPLOAD_DATA
        && self.status != GLU_STA_WAIT_RESULT
        && self.status != GLU_STA_UPLOAD_DATA_FAIL
        && self.status != GLU_STA_WAIT_RESULT_FAIL)
    {
        // 隐藏
        self.netTipsLabel.hidden = YES;
        return;
    }
    
}

-(void)showResult
{
    GluReportDetailVc *vc = [[GluReportDetailVc alloc]init];
    vc.dbGlucoseObj = self.dbGlucoseObj;
    vc.hidesBottomBarWhenPushed = YES;
    [self.weakNavControl pushViewController:vc animated:YES];
    
}

/// 状态机
/// - Parameter status: 界面状态
-(void)setStatus:(GLU_STA)status
{
    _status = status;
    if (self.stateChangeBLK) {
        self.stateChangeBLK(_status);
    }
    switch (self.status) {
        case GLU_STA_INIT:
        {
            if (self.tipTimer) {
                dispatch_source_cancel(self.tipTimer);
                self.tipTimer = nil;
            }
            self.startBtn.selected = NO;
            [self freshStartBtnBgColor];
            [self freshNetTips];
            self.startBtn.hidden = NO;
            
            self.gluNetObj = [[GluNetObj alloc]init];
            self.gluNetObj.maxCount = self.maxDataCount;
            self.gluNetObj.fasting = self.fasting;
            self.gluNetObj.within2HrsMeal = self.after_2_hor;
//            [self.circleProgressView setProgress:0 animated:NO];
            [self.circleProgressView  reset];
            self.uploadPPgDate = nil;
            self.reqResultDate = nil;
            self.measuringTipsLabel.hidden = YES;
            [self.tokenBucket stop]; // 令牌桶停止

        }
            break;
        case GLU_STA_COLLECTING: // 收集数据中
        {
            self.startBtn.hidden = NO;
            self.startBtn.selected = YES;
            [self freshStartBtnBgColor];
            self.measuringTipsLabel.hidden = NO;
            [self.tokenBucket start]; // 超时令牌桶启动

        }
            break;
        case GLU_STA_UPLOAD_DATA: // 上传ppg数据
        {
            self.startBtn.hidden = YES;
            self.startBtn.hidden = YES;
            self.startBtn.selected = NO;
            self.reReqBtn.hidden = YES;
            self.measuringTipsLabel.hidden = YES;
            
            [self.tokenBucket stop]; // 令牌桶停止
            
            [self freshStartBtnBgColor];
          
            if (!self.uploadPPgDate) {
                self.uploadPPgDate = [NSDate date];
            }

            if (self.tipTimer) {
                dispatch_source_cancel(self.tipTimer);
                self.tipTimer = nil;
            }
            
            
            WEAK_SELF
            self.tipTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
            dispatch_source_set_timer(self.tipTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
            dispatch_source_set_event_handler(self.tipTimer, ^{
                STRONG_SELF
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([[NSDate date] timeIntervalSinceDate:strongSelf.uploadPPgDate] >= 30) {
                        dispatch_source_cancel(strongSelf.tipTimer);
                        strongSelf.tipTimer = nil;
                    }
                    
                    [strongSelf freshNetTips];
                });
            });
            dispatch_activate(self.tipTimer);
            
            [self uploadPPgData];
          
            
        }
            break;
        case GLU_STA_UPLOAD_DATA_FAIL:
        {
            self.startBtn.hidden = YES;
            self.measuringTipsLabel.hidden = YES;

            [self.reReqBtn setTitle:@"Re-upload" forState:UIControlStateNormal];
            self.reReqBtn.hidden = NO;
            [self freshNetTips];

        }
            break;
        case GLU_STA_WAIT_RESULT: // 等待获取结果
        {
            self.startBtn.hidden = YES;
            self.reReqBtn.hidden = YES;
            self.measuringTipsLabel.hidden = YES;

            if (!self.reqResultDate) {
                self.reqResultDate = [NSDate date];
            }
            
//            [self freshNetTips];
            if (self.tipTimer) {
                dispatch_source_cancel(self.tipTimer);
                self.tipTimer = nil;
            }
            WEAK_SELF
            self.tipTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
            dispatch_source_set_timer(self.tipTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
            dispatch_source_set_event_handler(self.tipTimer, ^{
                STRONG_SELF
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([[NSDate date] timeIntervalSinceDate:strongSelf.reqResultDate] >= 30) {
                        dispatch_source_cancel(strongSelf.tipTimer);
                        strongSelf.tipTimer = nil;
                    }
                    
                    [strongSelf freshNetTips];
                });
            });
            dispatch_activate(self.tipTimer);
            
            
            // 延时5秒 调用获取
//            WEAK_SELF
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                STRONG_SELF
//                NSString *tmpMid = @"49aee70c-0dcf-44fe-a4f5-f660e534eec6";
                //
                [strongSelf sendReqResult];
            });
            
          
            
        }
            break;
        case GLU_STA_WAIT_RESULT_FAIL:
        {
            self.reqResultDate = [NSDate date];
            self.startBtn.hidden = YES;
            [self.reReqBtn setTitle:@"Retry request" forState:UIControlStateNormal];
            self.reReqBtn.hidden = NO;
            [self freshNetTips];
            self.measuringTipsLabel.hidden = YES;

        }
            break;
        default:
            break;
    }
    
}


-(void)uploadPPgData {
    
    NSString *sn = CARingSDK.instance.currentDevice.snString;
    NSString *mac = CARingSDK.instance.currentDevice.macAddress;
    
    WEAK_SELF
    [self.gluNetObj gluNewSmp:HOSTNAME
                    DataArray:[self.gluNetObj packToReqDict]
                          Ltk:self.glu_ltk
                           SN:sn
                          Key:CARingSDK.instance.netKey
                          MacAddr:mac
                       Secret:CARingSDK.instance.netSecret
                 AndComplated:^(NSHTTPURLResponse * _Nullable httpResp, NSDictionary * _Nullable content, NSNumber *  _Nullable state)
     {
        STRONG_SELF
        DebugNSLog(@"上传血糖ppg 网络回调.  :%@", content);
        // 访问失败
        if (httpResp.statusCode != 200 || (state && state.intValue != 0) )
        {
            if ([[NSDate date] timeIntervalSinceDate:self.uploadPPgDate] <= 60 *1) {
                DebugNSLog(@"重发 ppg数据");
                [strongSelf uploadPPgData];
            } else {
                strongSelf.status = GLU_STA_UPLOAD_DATA_FAIL;
            }
        }
        // 访问成功
        if (state && state.intValue == 0)
        {
          
            strongSelf.status = GLU_STA_WAIT_RESULT;
            

        }
        
    } AndServerNil:^{
        
    }];
}

-(void)sendReqResult {
    
    NSString *sn = CARingSDK.instance.currentDevice.snString;
    NSString *mac = CARingSDK.instance.currentDevice.macAddress;
    WEAK_SELF
    [self.gluNetObj gluAnrSmp:HOSTNAME Mid:self.gluNetObj.mid
                           SN:sn
                          Key:CARingSDK.instance.netKey
                          MacAddr:mac
                       Secret:CARingSDK.instance.netSecret AndComplated:^(NSHTTPURLResponse * _Nullable httpResp, NSDictionary * _Nullable content, NSNumber *  _Nullable state) {
        STRONG_SELF
        // 访问成功
        if (state && state.intValue == 0)
        {

            DebugNSLog(@"血糖结果回包: %@", content);
            // 保存数据 并跳转
            self.dbGlucoseObj = [DmdbGlucose new];
            BOOL succ = [strongSelf.dbGlucoseObj parseFromNetDict:content];
            if (succ) {
                [self showResult];
//                strongSelf.dbGlucoseObj.account = AccountCenter.instance.currentAccount.account;
//                [strongSelf.dbGlucoseObj insert:^(BOOL isSucc) {
//                    STRONG_SELF
//                    [strongSelf showResult];
//                    
//                }];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    STRONG_SELF
                    strongSelf.status = GLU_STA_INIT;// 状态还原
                });
            }
        
            if (!succ) {
                strongSelf.status = GLU_STA_WAIT_RESULT_FAIL;
                return;
            }
        }
        
        if (httpResp.statusCode != 200 || (state && state.intValue != 0) )
        {
            if ([[NSDate date] timeIntervalSinceDate:strongSelf.reqResultDate] <= 60)
            {
                DebugNSLog(@"重发 请求结果");

                [strongSelf sendReqResult];
            } else {
                strongSelf.status = GLU_STA_WAIT_RESULT_FAIL;
            }
        }
        
    } AndServerNil:^{
        self.status = GLU_STA_WAIT_RESULT_FAIL;
    }];
    
}


#pragma  mark --蓝牙

-(void)caLedStateReport:(BOOL)on Led:(uint8_t)led Current:(uint8_t)current AutoDim:(uint8_t)autoDim Freq:(uint8_t)freq
{
    DebugNSLog(@"led单测状态回调 On:%d", on);
    if (on) {
        if (self.status == GLU_STA_INIT) {
            self.status = GLU_STA_COLLECTING;
        }
    }
    
    if (!on) {
        if (self.status == GLU_STA_WAIT_PPG_STOP && self.gluNetObj.isEnough) {
            // 收集满了停止
            self.status = GLU_STA_UPLOAD_DATA;
        }
        
        if (self.status == GLU_STA_COLLECTING && !self.gluNetObj.isEnough)
        {
            self.status = GLU_STA_INIT; // 取消测量

        }
//        else {
//          // 其他停止
//            self.status = GLU_STA_INIT;
//        }
    }
    
}



- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service {
    
    self.startBtn.enabled = YES;
}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service {
    self.startBtn.enabled = NO;

    if (self.status == GLU_STA_COLLECTING) {
        // 测量取消
        WEAK_SELF
        [self showAlertWarningWithTitle:@"Tips" Msg:@"Ring disconnected, measurement canceled!" btnOk:@"Sure" OkBLk:^{
            STRONG_SELF
            strongSelf.status = GLU_STA_INIT;
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        
    }
    
}



// 单色led测量数据回调
-(void)caLedPPgDataRep:(NSMutableArray<NSNumber *> *)dataArry
{
//    DebugNSLog(@"上报led %d 个", dataArry.count);
    if (self.status == GLU_STA_COLLECTING) {
        [self.tokenBucket chargeToken]; //令牌桶充值
        BOOL full = [self.gluNetObj addPPg:dataArry];
        
        if (full) {
            DebugNSLog(@"Blood sugar sent to stop 1!");

            [CARingSDK.instance functionTurnGlucosePPgMeasure:NO];
            
            self.status = GLU_STA_WAIT_PPG_STOP; // 等待停止
            // 进入请求状态
//            self.status = GLU_STA_UPLOAD_DATA;
        }
        // 进度条
        CGFloat progress = [self.gluNetObj progressPercentValue];
        DebugNSLog(@"Current quantity %ld", (long)self.gluNetObj.currentCount);

//        DebugNSLog(@"进度 %.4f", progress);
        [self.circleProgressView setProgress:progress animated:YES];
    }
    
}

-(void)caPPGMeasuState:(CAPpgMeasureState *)stateObj
{
    DebugNSLog(@"ppg 状态, 佩戴 %d, 调光:%d", stateObj.isWearing,stateObj.isDimming);
}


- (void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason
    Data:(nonnull NSData *)originData
{
    
        DebugNSLog(@"caBleCmdExcute %@", originData);

        if (cmd == EXCUTED_CMD_FUNCTIN_LED_MEA) { // led单测
            if (!isSucc) {
                NSString *string = [CADeviceInfo descryOfErrorReason:reason];
                if (string.length) {
                    [self showAlertWarningWithTitle:@"Tips" Msg:string btnOk:_L2(L_OK) OkBLk:^{
                        
                    } CancelBtn:nil CancelBlk:nil Compelete:nil];
                }
               
                return;
            }
            

            
        }
}


- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging { 
    
}


- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service { 
    
}


- (void)caBleDeviceInfo:(nonnull CADeviceInfo *)devInfo { 
    
}


- (void)caBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed { 
    
}


- (void)caBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature { 
    
}


- (void)caBleFailConnectPeripheral:(nonnull CBPeripheral *)peripheral Error:(nonnull NSError *)error { 
    
}


- (void)caBleHistoryDataCount:(NSInteger)count { 
    
}


- (void)caBleHistoryDataTimeout { 
    
}


- (void)caBleHistorySr03Data:(CAHistoryDataSR03 * _Nullable)hisData IsComplete:(BOOL)isComplete { 
    
}


- (void)caBleIsBinded:(BOOL)isBinded { 
    
}


- (void)caBleMeasureDuration:(NSInteger)seconds { 
    
}


- (void)caBleOEMAuthResult:(BOOL)authSucceddful { 
    
}


- (void)caBleRealtimeHRV:(nonnull NSNumber *)hrv BloodOxygen:(nonnull NSNumber *)bloodOxygen HeartRate:(nonnull NSNumber *)hr Status:(REALTIME_STATUS)status { 
    
}


- (void)caBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData { 
    
}



#pragma  mark --lazy
- (QMUIButton *)startBtn
{
    if (!_startBtn) {
        _startBtn = [[QMUIButton alloc]init];
        _startBtn.backgroundColor = UIColor.blueColor;
        
        _startBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        [_startBtn setTitle:@"Start" forState:UIControlStateNormal];
        [_startBtn setTitle:_L2(L_CANCEL) forState:UIControlStateSelected];
        
        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        
        [_startBtn addTarget:self action:@selector(startBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //        _startBtn.enabled = NO; // 初始不可用
    }
    return _startBtn;
}

-(QMUIButton *)selectBtn
{
    if (!_selectBtn) {
        QMUIButton *selectBtn = [[QMUIButton alloc]init];
        _selectBtn = selectBtn;
        _selectBtn.spacingBetweenImageAndTitle = 5.f;
        _selectBtn.contentEdgeInsets = UIEdgeInsetsMake(3, 10, 3, 10);
        [_selectBtn setImagePosition:QMUIButtonImagePositionRight];
        //        [_selectBtn setImage:[UIImage imageNamed:@"dev_loc_arow_dwm"] forState:UIControlStateNormal];
        [_selectBtn setTitle:@"Within 2 hours meal" forState:UIControlStateNormal]; // 默认
        [_selectBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_selectBtn setBackgroundColor:UIColor.lightGrayColor];
        _selectBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        _selectBtn.userInteractionEnabled = NO;
    }
    return _selectBtn;
}

-(QMUIButton *)reReqBtn
{
    if (!_reReqBtn) {
        _reReqBtn = [[QMUIButton alloc]init];
        _reReqBtn.backgroundColor = UIColor.blueColor;
        
        _reReqBtn.cornerRadius = ITEM_CORNOR_RADIUS;
        //        [_reReqBtn setTitle:_L(L_START_MEASURE) forState:UIControlStateNormal];
        //        [_reReqBtn setTitle:_L(L_CANCEL) forState:UIControlStateSelected];
        
        [_reReqBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        //        [_startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateSelected];
        
        [_reReqBtn addTarget:self action:@selector(reReqBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //        _startBtn.enabled = NO; // 初始不可用
    }
    return _reReqBtn;
}


-(CircularProgressView *)circleProgressView 
{
    if (!_circleProgressView)
    {
        _circleProgressView = [[CircularProgressView alloc] initWithFrame:CGRectZero];
        _circleProgressView.progressColor = UIColor.greenColor;//进度颜色
        _circleProgressView.trackColor = UIColor.lightGrayColor; // 轨道颜色
        _circleProgressView.lineWidth = 12.f;
        _circleProgressView.startCapColor = UIColor.blueColor;
        _circleProgressView.percentageLabel.font = [UIFont fontWithName:FONT_ARIAL_BOLD size:35.0f];
        _circleProgressView.midImageView.image = [UIImage imageNamed:@"glu_icon_abnormal"];
    }
    return _circleProgressView;
}

-(UILabel *)netTipsLabel
{
    if (!_netTipsLabel) {
        _netTipsLabel = [UILabel new];
        _netTipsLabel.numberOfLines = 0;
        _netTipsLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _netTipsLabel;
}

-(UILabel *)measuringTipsLabel
{
    if (!_measuringTipsLabel) {
        _measuringTipsLabel = [UILabel new];
        _measuringTipsLabel.numberOfLines = 0;
        _measuringTipsLabel.textAlignment = NSTextAlignmentCenter;
        _measuringTipsLabel.attributedText = [UIViewController bigSmallAttrString:[NSString stringWithFormat:@"%@\r\n\r\n", @"Measuring..."] FontA:[UIFont fontWithName:FONT_ARIAL_BOLD size:21] TxtColorA:UIColor.whiteColor StrB:@"Please keep your finger still during the measurement process, which takes about 5 minutes." FontB:[UIFont systemFontOfSize:16] TxtColorB:UIColor.lightGrayColor];
    }
    return _measuringTipsLabel;
}

-(TokenBucket *)tokenBucket
{
    if (!_tokenBucket)
    {
        WEAK_SELF
        _tokenBucket = [[TokenBucket alloc]init];
        _tokenBucket.intervalSecs = 1; // 每次1秒
        _tokenBucket.tokenCount = 2; // 2次
        _tokenBucket.timeoutBlock = ^{
            STRONG_SELF
            [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"The ring is not worn, measurement stopped!" btnCancel:@"Sure" Compelete:^{
                // 停止测量, 重置
            }];
            strongSelf.status = GLU_STA_INIT;
        };
    }
    return _tokenBucket;
}

-(void)dealloc
{
    [self.tokenBucket stop];
}


@end
